define(function () {

  /**
   * [Pagination description]
   * @param {jQuery Object} $dom  分页容器
   * @param {Function} cb         回调
   * @param {Object}   config     输入参数
   */
  function Pagination($dom, cb, config) {
    var _this = this
    this.filter = {}

    var defaultConfig = {
      page: 0, //第几页
      perPage: 30 //每页个数
    }

    $.extend(this.filter, defaultConfig, config)

    var pageNumber = new PageNumber({
      perpage: this.filter.perPage
    })

    //刷新列表
    this.updateData = function () {
      pageNumber.goto(_this.filter.page)
    }

    this.searchData = function () {
      pageNumber.goto(0)
    }

    //加载所有数据
    this.reloadData = function () {
      this.filter = {
        page: this.filter.page,
        perPage: this.filter.perPage
      }
      pageNumber.goto(0)
    }

    pageNumber.$dom.appendTo($('.pagination').html(''))
    pageNumber.pageCallback = function (newPageNum) {
      // console.log(newPageNum);
      if(newPageNum !== undefined) {
        _this.filter.page = newPageNum
      }

      cb(_this.filter, function (data) {
        if(!data.list.length) {
          pageNumber.$dom.hide()
        } else {
          pageNumber.$dom.show()
        }
        pageNumber.data.max = Math.ceil(data.pager.total / _this.filter.perPage) - 1
        pageNumber.update()
      });
    }

    function pageChange() {
      var startSn = _this.filter.page * _this.filter.perPage
      _this.filter.perPage = parseInt(pageNumber.perpageInput.value())
      _this.filter.page = Math.floor(startSn / _this.filter.perPage)
      pageNumber.goto(_this.filter.page)
    }

    pageNumber.perpageInput.$input.on('keyup', function (e) {
      if(e.keyCode == 13) {
        pageChange()
      }
    })

    pageNumber.$perpageBtn.on('click', function () {
      pageChange()
    })
    pageNumber.goto(0);
  }

  window.Pagination = Pagination
  return Pagination
})
